﻿using BBCore.Application.Service;
using BBCore.Core.Models.Admins;
using BBCore.Core.Models.Samples;
using BBCore.Infrastructure.Helps;
using BBCore.Server.Components.Pages.Admins;
using BBCore.Server.Services;
using BootstrapBlazor.Components;
using ClosedXML.Excel;
using DocumentFormat.OpenXml.Drawing.Diagrams;
using DocumentFormat.OpenXml.InkML;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;
using System.Diagnostics.CodeAnalysis;


namespace BBCore.Server.Components.Pages.Samples
{
    public partial class HYJ_MasterDetail_Modal
    {
        private Table<HYJ_Master_Table>? _mastertable;
        [Inject] private RecordLockService LockService { get; set; } = default!;

        private async Task<QueryData<HYJ_Master_Table>> OnMasterQueryAsync(QueryPageOptions option) =>
            await IMasterDataQueryService.OnQueryAsync(option, q => q.OrderByDescending(x => x.HEAD_ID));

        public async Task AddRecord()
        {
            var result = await DialogService.ShowModal<HYJ_Master_Details_Modal>(new ResultDialogOption()
            {
                Title = "新建",
                FullScreenSize = FullScreenSize.Always,
                ShowMaximizeButton = true,
                IsDraggable = true,
                ShowFooter = false,
                ComponentParameters = new Dictionary<string, object>()
                {
                    [nameof(HYJ_Master_Details_Modal.Model)] = new HYJ_Master_Table(),
                    [nameof(HYJ_Master_Details_Modal.OnSaveSuccess)] = (Action<DialogResult>)(async result =>
                    {
                        await HandleDialogResult(DialogResult.Yes);
                    })
                }
            });
        }
        private async Task HandleDialogResult(DialogResult result)
        {
            if (result == DialogResult.Yes)
            {
                if (_mastertable != null)
                {

                    await _mastertable.QueryAsync();
                }
                else
                {
                    await ShowToastMessageAsync("错误,主从主Table未初始化", ToastCategory.Error);
                }
            }

        }
        public async Task EditRecord(HYJ_Master_Table context)
        {
            var lockKey = GetLockKey< HYJ_Master_Table,HYJ_Detail_Table,int>(context);
            var currentUser = Username; // 确保获取正确的用户名（如从身份验证服务获取）

            // 检查锁定状态（通过注入的服务）
            if (LockService.TryGetLockUser(lockKey, out var editingUser))
            {
                await ShowSwalMessageAsync($"{editingUser} 正在编辑该记录，请稍后再试。", SwalCategory.Warning);
                return;
            }

            // 添加锁定（通过服务）
            LockService.AddLock(lockKey, currentUser);

            try
            {
                var lst = await freeSql.Select<HYJ_Master_Table>().Where(a => a.HEAD_ID == context.HEAD_ID).IncludeMany(b => b.Details).FirstAsync();
                var dialog = await DialogService.ShowModal<HYJ_Master_Details_Modal>(new ResultDialogOption()
                {
                    Title = "编辑",
                    FullScreenSize = FullScreenSize.Always,
                    ShowMaximizeButton = true,
                    IsDraggable = true,
                    ShowFooter = false,
                    ComponentParameters = new Dictionary<string, object>()
                    {
                        [nameof(HYJ_Master_Details_Modal.Model)] = lst,
                        [nameof(HYJ_Master_Details_Modal.OnSaveSuccess)] = (Action<DialogResult>)(async result =>
                        {
                            LockService.RemoveLock(lockKey);
                            await HandleDialogResult(DialogResult.Yes);
                        })
                    }
                });
            }
            catch (Exception ex)
            {
                LockService.RemoveLock(lockKey);
                await ShowSwalMessageAsync("出错了:" + ex.ToString(), SwalCategory.Error);
            }
            finally
            {
                // 确保无论弹窗如何关闭，最终释放锁

                LockService.RemoveLock(lockKey);
            }
        }
        /// <summary>
        /// 级联删除
        /// </summary>
        /// <param name="items">IEnumerable<Tmodel></param>
        /// <returns>Task<bool></returns>
        private async Task<bool> OnDeleteAsync(IEnumerable<HYJ_Master_Table> items)
        {
            foreach (var item in items)
            {
                var lockKey = GetLockKey<HYJ_Master_Table, HYJ_Detail_Table, int>(item);
                if (LockService.TryGetLockUser(lockKey, out var user))
                {
                    await ShowSwalMessageAsync($"{user} 正在编辑该记录，无法删除。", SwalCategory.Warning);
                    return false;
                }
            }
            // 执行删除...
            var repo = freeSql.GetRepository<HYJ_Master_Table>();
            foreach (var item in items)
            {
                repo.DeleteCascadeByDatabase(a => a.HEAD_ID == item.HEAD_ID);
            }
            return await Task.FromResult(true);
        }

        private readonly ExportDataFile _export = new();
        private async Task exportdata()
        {
            var lst = freeSql.Select<HYJ_Master_Table>().IncludeMany(a => a.Details).ToList();
            //using IXLWorkbook workbook = ClosedxmlExcelExportService.ExportMasterDetailAuto(lst, o => o.Details!, "结果");
            //await _export.ExportAsExcelAsync(JSRuntime, workbook, "结果", MimeType.Excel);
            // 定义主表列头和明细表列头
            var masterColumns = new List<(string Header, Func<HYJ_Master_Table, object> Selector)>
              {
                  ("JOB_NO", order => order.JOB_NO),
                  ("日期", order => order.REQ_DATE.ToString("yyyy-MM-dd")),
                  ("数量", order => order.QUANTITY)
              };

            var detailColumns = new List<(string Header, Func<HYJ_Detail_Table, object> Selector)>
              {
                  ("部品号", detail => detail.ITEM!),
                  ("LEVEL2", detail => detail.LEVEL2!)

              };
            using IXLWorkbook workbook = ClosedxmlExcelExportService.ExportMasterDetail(
                 lst,
                 order => order.Details!,  // 明细选择器
                 "测试",
                 masterColumns,
                 detailColumns
             );
            await _export.ExportAsExcelAsync(JSRuntime, workbook, "结果", MimeType.Excel);
        }
    }
}
